﻿using System;
using Webshop20.Application.Queries.Messages;
using Webshop20.Domain.Common.Exceptions;
using Webshop20.Domain.Security.Authentication.Services.Contracts;

namespace Webshop20.Application.Queries.Services
{
    public interface ILoginService : IService{}

    public class LoginService : ServiceBase, ILoginService
    {
        private readonly IAuthenticationService authenticationService;
        
        public LoginService(IAuthenticationService authenticationService)
        {
            this.authenticationService = authenticationService;
            
        }

        void authenticationService_DomainFailure(DomainMessageSentEventArgs args, object sender)
        {
            domainMessage = args.SystemMessage;
        }

        public override ISystemMessage Handle(ISystemMessage request)
        {
            var authenticateUserRequest = request as LoginRequest;
            var authenticationResult = false;
            var accountId = 0;
            try
            {
                authenticationResult = authenticationService.AuthenticateUser(
                    authenticateUserRequest.UserName,
                    authenticateUserRequest.Password,
                    out accountId
                    );
            }
            catch (DomainException ex)
            {
                HandleDomainException(ex.DomainMessage);
            }


            return new LoginResponse(authenticationResult, accountId, domainMessage);

            //if (authenticationService.AuthenticateUser(userName, password, out loginAttempts))
            //{
            //    operationSuccess = true;
            //    return new QueryResult<object>(operationSuccess, null, errors);
            //}
            //if (loginAttempts > VALUES.MAX_LOGIN_ATTEMPTS)
            //    errors.Add(new RuleFailure("LoginUCC", string.Empty, "Authenticate", null, localisationService.GetText(ERRORS.ACCOUNT_LOCKED)));
            ////"Der Account wird für eine halbe Stunde gesperrt";
            //else
            //    errors.Add(new RuleFailure("LoginUCC", string.Empty, "Authenticate", null, localisationService.GetText(ERRORS.LOGIN_FAILURE)));
            //// "Login fehlgeschlagen. Benutzername oder Passwort falsch"; 
            //operationSuccess = false;
            //return new QueryResult<object>(operationSuccess, null, errors);
        }
    }
}
